/*
* @(#)ListAlertMessageHomeAction.java
*
* Copyright (c) 2004 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
*/
package com.dcivision.framework.web;

import java.sql.Connection;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.alert.AlertOperationConstant;
import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertLogAction;
import com.dcivision.alert.bean.UpdateAlertSystemLog;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.alert.core.MessageFormatter;
import com.dcivision.alert.core.MessageFormatterFactory;
import com.dcivision.alert.dao.UpdateAlertDAObject;
import com.dcivision.calendar.bean.CalendarRecord;
import com.dcivision.calendar.dao.CalendarRecordDAObject;
import com.dcivision.dms.bean.DmsCheckoutHistory;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.core.VersionControlManager;
import com.dcivision.forum.core.ForumManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.user.bean.UserDelegation;
import com.dcivision.user.dao.UserDelegationDAObject;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.dao.WorkflowProgressDAObject;

/**
 * <p>Class Name:       ListAlertMessageHomeAction.java    </p>
 * <p>Description:      The list action class for Alert Messages Home.jsp</p>
 *
 *  @author          Beyond Qu
 *  @company         DCIVision Limited
 *  @creation date   11/08/2004
 *  @version         $Revision: 1.9.2.1 $
 */

public class ListAlertMessageHomeAction  extends ListPersonalHomeAction {

  public static final String REVISION = "$Revision: 1.9.2.1 $";

  //Personal Home List Type constants.
  public final static String VAR_ALERT_CALENDARTOLIST = GlobalConstant.HOME_CALENDAR_TODO_LIST;
  public final static String VAR_ALERT_CALENDAREVENTLIST = GlobalConstant.HOME_CALENDAR_EVENT_LIST;
  public final static String VAR_ALERT_CALENDARMEETINGLIST = GlobalConstant.HOME_CALENDAR_MEETING_LIST;
  public final static String VAR_ALERT_SYSTEM_LOG = GlobalConstant.HOME_SYSTEM_LOG_LIST;
  public final static String VAR_RECENTLY_ACCESS = GlobalConstant.HOME_RECENTLY_ACCESS_LIST;
  public final static String VAR_WORKFLOW_TASK_LIST = GlobalConstant.HOME_WORKFLOW_TASK_LIST;
  public final static String VAR_WORKFLOW_TRACKING_LIST = GlobalConstant.HOME_WORKFLOW_TRACKING_LIST;

  /**
   *  Constructor - Creates a new instance of ListPersonalHomeAction and define the default listName.
   */
  public ListAlertMessageHomeAction() {
    super();
    this.setListName("alertSystemLogList");
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    form = form == null ? new ListAlertMessageHomeForm() :(ListAlertMessageHomeForm) form ;
    ListAlertMessageHomeForm listForm = (ListAlertMessageHomeForm) form ;

    String updateAlertSystemLogID = (String)request.getAttribute("updateAlertSystemLogID");
    listForm.setPageOffset("10000");
    listForm.setDisableActionType("");
    if(!Utility.isEmpty( request.getParameter("opMode"))){
         listForm.setOpMode(request.getParameter("opMode"));   
    }
    
    if(!Utility.isEmpty( request.getParameter("actionSystemLogID"))){
         listForm.setActionSystemLogID(TextUtility.parseIntegerObj(request.getParameter("actionSystemLogID")));   
    }  

    if(!Utility.isEmpty( request.getParameter("disableActionType"))){
         listForm.setDisableActionType(request.getParameter("disableActionType"));   
    }  

    
    String opMode = listForm.getOpMode();
    log.debug("opMode = " + opMode);

    // Set function code if necessary.
    if (!Utility.isEmpty(listForm.getCurFunctionCode())) {
      this.setFunctionCode(listForm.getCurFunctionCode());
    }

    // Set the function code for current action.
//    ActionForward forward = mapping.findForward("L");
//    if (forward!=null) {return forward;}
    if (GlobalConstant.OP_MODE_LIST_DELETE.equals(listForm.getOpMode())) {
      try {
        this.deleteScheduleListData(mapping, listForm, request, response);        
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
    }

    if (AlertOperationConstant.READ_OPERATION.equals(listForm.getOpMode()) || 
        AlertOperationConstant.UNREAD_OPERATION.equals(listForm.getOpMode())
       ) {
      try {
        this.updateReadOperationLog(mapping, listForm, request, response);
        this.commit(request);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
    }
    
    // Get current user's disable view channels
//    this.getCurrentUserDisableViewChannels((AbstractSearchForm)form,request);
    
//    return super.execute(mapping, form, request, response);
    
    if (listForm != null && GlobalConstant.OP_MODE_LIST_RETAIN.equals(((AbstractSearchForm)listForm).getOpMode())) {
      // Retain the attributes of search form.
      if ((ActionForm)request.getSession().getAttribute(this.m_sListName)!=null) {
        //listForm = (ActionForm)request.getSession().getAttribute(this.m_sListName);
        request.setAttribute(mapping.getAttribute(), listForm);
      } else {
        request.getSession().setAttribute(this.m_sListName, listForm);
      }
    } else {
      // Set the search from into session for remembering the settings.
      request.getSession().setAttribute(this.m_sListName, listForm);
    }

    AbstractSearchForm searchForm = listForm;
    log.info(this.getClass().getName()+", OP Mode:"+searchForm.getOpMode()+", Nav Mode:"+searchForm.getNavMode());

    // Set the function code for current action.
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }

    if (GlobalConstant.OP_MODE_LIST_DELETE.equals(searchForm.getOpMode())) {
      try {
        this.deleteListData(mapping, searchForm, request, response);
        this.commit(request);
        addMessage(request, MESSAGE_RECORDS_DELETED, ""+searchForm.getBasicSelectedID().length);
        searchForm.setBasicSelectedID(null);
        searchForm.setOpMode(null);

        // Check for all item deletes per page
        this.getListData(mapping, searchForm, request, response);
      } catch (ApplicationException e) {
        this.rollback(request);
        this.handleApplicationException(request, e);
        request.setAttribute(this.m_sListName, new ArrayList());
      }
    } else {
      try {
        this.getListData(mapping, searchForm, request, response);
      } catch (ApplicationException e) {
        this.handleApplicationException(request, e);
        request.setAttribute(this.m_sListName, new ArrayList());
      }
    }

    List resultList = (List)request.getAttribute(this.m_sListName);
    while ( (resultList.size()==0) && (TextUtility.parseInteger(searchForm.getCurStartRowNo())>TextUtility.parseInteger(searchForm.getPageOffset())) ) {
      int prvRowNo = TextUtility.parseInteger(searchForm.getCurStartRowNo())-TextUtility.parseInteger(searchForm.pageOffset);
      searchForm.setCurStartRowNo(TextUtility.formatInteger(prvRowNo));
      this.getListData(mapping, searchForm, request, response);
    }

    //view system log message
    if(!Utility.isEmpty(request.getAttribute("viewMessage"))){
      request.setAttribute("updateAlertSystemLogID",updateAlertSystemLogID);  
      return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
    }
    
    return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
    
    
  }

  /**
   *  Method getListData() - retrieve the appropriate item list for current page
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @return     void
   *  @throws     ApplicationException  Throws Exception if cannot get the list data from DAO object
   */
  public synchronized void getListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    List sysLogList = new ArrayList();
    List alertMessgesList = new ArrayList();
    
    ListAlertMessageHomeForm listHomeForm = (ListAlertMessageHomeForm)form;

    // According to the attribute name to call the corresponding list retrieval function for personal home.
    if (VAR_ALERT_SYSTEM_LOG.equals(listHomeForm.getCurrListType())) {
      log.debug("Getting System Log...");
      listHomeForm.setSystemLogsCurStartRowNo(form.getCurStartRowNo());
    }

    sysLogList = this.getSystemLogList(request, listHomeForm);
    
    for(int i = 0 ;i<sysLogList.size() ;i++){
        UpdateAlertSystemLog updateAlertSystemLog = (UpdateAlertSystemLog)sysLogList.get(i);
        String[] messageArrary = getMessageLogNew(request,updateAlertSystemLog);
        alertMessgesList.add(messageArrary);
    }

    request.setAttribute(ListPersonalHomeAction.VAR_ALERT_SYSTEM_LOG, alertMessgesList);
    //request.setAttribute("alertMessgesList", alertMessgesList);
  }

  public String[] getMessageLog (HttpServletRequest request ,UpdateAlertSystemLog updateAlertSystemLog){
        String[] outArrary = new String[5];
        String outID = updateAlertSystemLog.getID()+"";
        String outIsRead = "";
        String outStr = "";
        String outURL = "";
        String outDataTime = "";

        
        String accessCalendars = "true";  
        Connection dbConn = this.getConnection(request);
        SessionContainer  sessionContainer =this.getSessionContainer(request);
      
        int     COLUMN_OFFSET = 1;
      
        PermissionManager permissionManager = sessionContainer.getPermissionManager();
        UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer, dbConn);
        DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer,dbConn);
        CalendarRecordDAObject calendarRecordDAO = new CalendarRecordDAObject(sessionContainer,dbConn);
        AlertManager alertManager = new AlertManager(sessionContainer, dbConn);
        VersionControlManager verControlManager = new VersionControlManager(sessionContainer,dbConn);
        DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer,dbConn);
        ForumManager forumManager=new ForumManager(sessionContainer,dbConn);

        try{
          String selectedID = "";
          String userName = "";
          String actionType = "";
          String objectType = "";
          String location = "";
          String objectName = "";
          String actionDate = "";
          String atOrBefore = "";
          String underFolder = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.underFolder");    //"under folder";
          String expired = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.label.will_be_expired");    //"will be expired ";
          String checkIn =MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.label.is_automatic_checked_in");    //"is automatic checked in ";
          String permission = "";
          String status = "";
          boolean inviteToRead = false;
          boolean readDetails = false;
          Integer checkoutPersonID = new Integer("0");
        
          boolean invitSelf = false ;//invit self ,dont show invit message
          //workflow
          String recordID = "";
          String trackID = "";
          String currentUserName = UserInfoFactory.getUserFullName(sessionContainer.getUserRecordID());
          String isReminded    = "";
        
          DmsDocument dmsDocument = new DmsDocument();
          DmsDocument documentRoot = new DmsDocument();
            CalendarRecord calendarRecord = new CalendarRecord();
          userName=UserInfoFactory.getUserFullName((updateAlertSystemLog).getActionUserID());
        
          UpdateAlert updateAlert = null;
        
          try {
            /* Action String Defintion */
            if (UpdateAlert.CREATE_ACTION.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_create");     //"has created a ";
        
            }//For Delete Action
            else if (UpdateAlert.DELETE_ACTION.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_delete");     //"has deleted a ";
        
            }//For Update Action
            else if (UpdateAlert.UPDATE_ACTION.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_update");     //"has updated a ";
        
            }//For View Action
            else if (UpdateAlert.VIEW_ACTION.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_view");       //"has viewed a ";
        
            }//For Relationship Action
            else if (UpdateAlert.MODIFY_RELATED_DOC.equals((updateAlertSystemLog).getActionType())){
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"home.log.actionType_modify");
              underFolder = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"home.log.that_has_the") + 
                            " " + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"dms.label.document_relationship_linkage") + " " 
                                                        + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"home.log.to");
              
            }//For Invite Action
            else if (UpdateAlert.INVITE_ACTION.equals((updateAlertSystemLog).getActionType())) {
        
              //for calender invite
              if (UpdateAlert.CALENDAR_INACTIVE_TYPE.equals((updateAlertSystemLog).getObjectType())||UpdateAlert.CALENDAR_MODIFY_TYPE.equals((updateAlertSystemLog).getObjectType())||UpdateAlert.CALENDAR_TYPE.equals((updateAlertSystemLog).getObjectType())){
                updateAlert = (UpdateAlert) updateAlertDAO.getObjectByID((updateAlertSystemLog).getUpdateAlertID());
                //calendarRecord = (CalendarRecord)calendarRecordDAO.getObjectByID(updateAlert.getObjectID());
                calendarRecord = (CalendarRecord)calendarRecordDAO.getOriCalendarByID(updateAlert.getObjectID());
        
                objectName = calendarRecord.getTitle();
                selectedID = calendarRecord.getID().toString();
        
                if(calendarRecord.getCreatorID().intValue() == sessionContainer.getUserRecordID().intValue())
                  invitSelf = true;
        
                if (GlobalConstant.RECORD_CANCELLED.equals(updateAlert.getRecordStatus())) {
                  actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_cancel");    //"has cancelled the ";
                  isReminded = "&isReminded=true";
                }else {
                  if(UpdateAlert.CALENDAR_MODIFY_TYPE.equals((updateAlertSystemLog).getObjectType())){
                    actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_notify_meeting");
                    isReminded = "&isReminded=true";
                  }else if(UpdateAlert.CALENDAR_INACTIVE_TYPE.equals((updateAlertSystemLog).getObjectType())){
                    actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_cancel");
                    isReminded = "&isReminded=true";
                  }else{
                  actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_invite_attend");  //"has invited you to attend a ";
                  }
               }
               //For DMS invite
              }else{
                actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_invite_read");  //"has invited you to read a ";
                if (SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.DMS_INVITATION_OVERWRITE_STANDARD)){
                  inviteToRead = true;
                }
              }
             
            }//invite to discuss
            else if(UpdateAlert.DISCUSS_ACTION.equals((updateAlertSystemLog).getActionType())){
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_invite_dicuss");
            }//For Remind Action
            else if (UpdateAlert.REMIND_ACTION.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_remind");  //"please be reminded that a ";
              updateAlert = (UpdateAlert) updateAlertDAO.getObjectByID((updateAlertSystemLog).getUpdateAlertID());
              if (UpdateAlert.CALENDAR_TYPE.equals(updateAlert.getObjectType())){
        //        calendarRecord = (CalendarRecord)calendarRecordDAO.getObjectByID(updateAlert.getObjectID());
                calendarRecord = (CalendarRecord)calendarRecordDAO.getOriCalendarByID(updateAlert.getObjectID());
                objectName = calendarRecord.getTitle();
                selectedID = calendarRecord.getID().toString();
                isReminded    = "&isReminded=true";
              }
            }//For Workflow Action NOTIFY_TASK_COMPLETED_ACTION
            else if (UpdateAlert.NOTIFY_TASK_COMPLETED_ACTION.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.notify");  //"please be notified that a ";
              status = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_task_completed");  //"has been completed ";
        
            }//For Workflow Action NOTIFY_TASK_ARRIVED_ACTION
            else if (UpdateAlert.NOTIFY_TASK_ARRIVED_ACTION.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.notify");  //"please be notified that a ";
              status = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_task_arrived");  //"has been arrived ";
        
            }//For Workflow Action NOTIFY_TASK_OWNER_OVERDUE_ACTION
            else if (UpdateAlert.NOTIFY_TASK_OWNER_OVERDUE_ACTION.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.notify");  //"please be notified that a ";
              status = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_task_owner_over_due");  //"has been overdue ";
        
            }//For Workflow Action NOTIFY_TASK_ALL_OVERDUE_ACTION
            else if (UpdateAlert.NOTIFY_TASK_ALL_OVERDUE_ACTION.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.notify");  //"please be notified that a ";
              status = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_task_all_over_due");  //"has been all overdue ";
        
            }//For Workflow Action NOTIFY_STOP_TRACK
            else if (UpdateAlert.NOTIFY_STOP_TRACK.equals((updateAlertSystemLog).getActionType())) {
              actionType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.notify");  //"please be notified that a ";
              status = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_task_track_stop");  //"has been all stop ";
            }// For Workflow Delegation Action
            else if (UpdateAlert.DELEGATION_ACTION.equals((updateAlertSystemLog).getActionType())) {
              objectType = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectType_workflow_task");
              status = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.actionType_delegate");
            }
            /* End of Action String Definitinon */
            if (UpdateAlert.DOCUMENT_TYPE.equals((updateAlertSystemLog).getObjectType())||UpdateAlert.AUTOMATE_CHECKIN.equals((updateAlertSystemLog).getObjectType())){
              objectType=MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectType_document"); //"document ";
        
              //Check Permission
              dmsDocument = docRetrievalManager.getDocument((updateAlertSystemLog).getObjectID());
              documentRoot = docRetrievalManager.getRootFolderByRootID(dmsDocument.getRootID());
        
              permission = permissionManager.getPermission(dbConn,GlobalConstant.OBJECT_TYPE_DOCUMENT, dmsDocument.getID());
              readDetails = true;
        
              if (DmsVersion.EXCLUSIVE_LOCK.equals((dmsDocument).getItemStatus())) {
                DmsCheckoutHistory checkoutHistory = verControlManager.getCheckoutHistory((dmsDocument).getCheckoutID());
                checkoutPersonID = checkoutHistory.getCheckoutPersonID();
              }
        
              //Check for Document Reminder
              if (UpdateAlert.REMIND_ACTION.equals((updateAlertSystemLog).getActionType())) {
                objectName = dmsDocument.getDocumentName();
                selectedID = dmsDocument.getID().toString();
        
              }
            }// For Workflow
            else if (UpdateAlert.WORKFLOW_TYPE.equals((updateAlertSystemLog).getObjectType())){
              objectType=MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectType_workflow"); //"workflow step ";
        
              readDetails = false;
              selectedID = (updateAlertSystemLog).getObjectID().toString();
        
              WorkflowProgressDAObject progressDAO = new WorkflowProgressDAObject(sessionContainer, dbConn);
              WorkflowProgress workflowProgress = (WorkflowProgress)progressDAO.getObjectByID(new Integer(selectedID));
              WorkflowStep workflowStep = workflowProgress.getWorkflowStepSource();
        
              //Check for Workflow Step details
              objectName = workflowStep.getStepSeq() + ". " + workflowStep.getStepName();
              recordID = workflowProgress.getWorkflowRecordID().toString();
              trackID = workflowProgress.getTrackID().toString();
        
              //Check for due date
              if (workflowStep.getOnNoResponseAfter() != null) {
                 actionDate = TextUtility.formatDate(workflowStep.getOnNoResponseAfter(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DATETIME_FORMAT));
                 atOrBefore = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.atOrBefore_before");    //"before";
              }
              else if (workflowStep.getOnNoResponseFor() != null) {
                long tmp = workflowProgress.getCreateDate().getTime();
                tmp += workflowStep.getOnNoResponseFor().intValue() * 24 * 60 * 60 * 1000;
                Timestamp dueDate = new Timestamp(tmp);
                actionDate = TextUtility.formatDate(dueDate, SystemParameterFactory.getSystemParameter(SystemParameterConstant.DATETIME_FORMAT));
                atOrBefore = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.atOrBefore_before");    //"before";
              }
            }
        
            if (UpdateAlert.INVITE_ACTION.equals((updateAlertSystemLog).getActionType())) {
              if (UpdateAlert.DOCUMENT_TYPE.equals((updateAlertSystemLog).getObjectType())){
                 actionDate = TextUtility.formatTimestampToDate((updateAlertSystemLog).getDueDate());
                 if ((updateAlertSystemLog).getDueDate()!=null )
                    atOrBefore = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"home.log.atOrBefore_before");    //"before";
        
              }else{
                 actionDate = TextUtility.formatTimestampToDate((updateAlertSystemLog).getActionDate());
                 if ((updateAlertSystemLog).getActionDate()!=null )
                    atOrBefore = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"home.log.atOrBefore_before");    //"before";
        
              }
              if(Utility.isEmpty(actionDate) && UpdateAlert.INVITE_ACTION.equals((updateAlertSystemLog).getObjectType())){
                actionDate = TextUtility.formatTimestamp(calendarRecord.getDatetime());
                atOrBefore = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"home.log.atOrBefore_before");    //"before";
              }
            } else if ((UpdateAlert.REMIND_ACTION.equals((updateAlertSystemLog).getActionType())) ) {
                actionDate=TextUtility.formatTimestampToDate((updateAlertSystemLog).getActionDate());
              if ((updateAlertSystemLog).getActionDate()!=null )
                  atOrBefore = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"home.log.atOrBefore_at");     //"at";
            }
            if (calendarRecord != null) {
              if (CalendarRecord.EVENT_TYPE_CALENDAR_EVENT.equals(calendarRecord.getEventType())) {
                objectType=MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectType_event"); //"event ";
              } else if (CalendarRecord.EVENT_TYPE_CALENDAR_MEETING.equals(calendarRecord.getEventType())) {
                objectType=MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectType_meeting"); //"meeting ";
              } else if (CalendarRecord.EVENT_TYPE_CALENDAR_TODO.equals(calendarRecord.getEventType())) {
                objectType=MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectType_todo"); //"meeting ";
              }
            }
          } catch (Exception e) {
            log.error(e, e);
          }
        
        
          //List all  calendar SystemLog
          if (((UpdateAlert.CALENDAR_TYPE.equals((updateAlertSystemLog).getObjectType())) || (UpdateAlert.INVITE_TYPE.equals((updateAlertSystemLog).getObjectType())) || (UpdateAlert.CALENDAR_MODIFY_TYPE.equals((updateAlertSystemLog).getObjectType())) || (UpdateAlert.CALENDAR_INACTIVE_TYPE.equals((updateAlertSystemLog).getObjectType())) ) && ("false".equals(accessCalendars)||invitSelf)){
          }
          else if ((UpdateAlert.CALENDAR_MODIFY_TYPE.equals((updateAlertSystemLog).getObjectType())||UpdateAlert.CALENDAR_INACTIVE_TYPE.equals((updateAlertSystemLog).getObjectType())) && "true".equals(accessCalendars)){
            if (alertManager.checkForSystemLogActionByActionType((updateAlertSystemLog).getID(), UpdateAlertLogAction.READ_ACTION)) {
              outIsRead = "read"; 
            }else{
              outIsRead = "unread"; 
            }
            if(UpdateAlert.CALENDAR_MODIFY_TYPE.equals((updateAlertSystemLog).getObjectType()))
              objectType="";
              outStr +=  " "+userName; 
              outStr +=  " "+actionType;
              outStr +=  " "+objectType;
              outStr +=  " "+status; 
//              outStr += "\"";
              if (UpdateAlert.CALENDAR_MODIFY_TYPE.equals((updateAlertSystemLog).getObjectType())||UpdateAlert.CALENDAR_INACTIVE_TYPE.equals((updateAlertSystemLog).getObjectType())){ 
                 //outStr +=  " "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectName_calendar");
                 if(!GlobalConstant.RECORD_STATUS_INACTIVE.equals(calendarRecord.getRecordStatus())){
                   outURL = "/calendar/MaintCalendar.do?navMode=V&isHome=true&isHome=true&isHome=true&isHome=true&opReply=True&ID="+selectedID+"&systemLogID="+(updateAlertSystemLog).getID()+""+isReminded+"";
                 }
                 outStr +=  " "+objectName;
              }
              if (UpdateAlert.CALENDAR_MODIFY_TYPE.equals((updateAlertSystemLog).getObjectType())||UpdateAlert.CALENDAR_INACTIVE_TYPE.equals((updateAlertSystemLog).getObjectType())){ 
                //if todo canlenar take out time part
                if (CalendarRecord.EVENT_TYPE_CALENDAR_TODO.equals(calendarRecord.getEventType())) { 
                  outStr += " [ "+ TextUtility.formatTimestamp(calendarRecord.getDatetime()).substring(0,10) +" ]";
                }else{
                  outStr += " [ "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "common.label.period_from") +TextUtility.formatTimestamp(calendarRecord.getDatetime())+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "common.label.period_to")
                  +TextUtility.formatTimestamp(calendarRecord.getEndtime())+" ]";
                }
              }
        
              outStr +=  " "+atOrBefore;
              outStr +=  " "+actionDate;
        
              if (readDetails) {
                String message = TextUtility.escapeJSString((updateAlertSystemLog).getMessage());
                //if(!Utility.isEmpty(message)){
                    outURL = "/ListUpdateAlertSummary.do?objectType=" + (updateAlertSystemLog).getObjectType() + "&objectID=" + (updateAlertSystemLog).getObjectID() + "&actionType=" + (updateAlertSystemLog).getActionType() + "&updateAlertID=" + (updateAlertSystemLog).getUpdateAlertID() + "&updateAlertTypeID=" + (updateAlertSystemLog).getUpdateAlertTypeID() + "&updateAlertSystemLogID=" + (updateAlertSystemLog).getID() + "&message=&updateReadOperation=true";
                //}
              }
              outDataTime = TextUtility.formatTimestamp((updateAlertSystemLog).getCreateDate());
      }else{
        if (alertManager.checkForSystemLogActionByActionType((updateAlertSystemLog).getID(), UpdateAlertLogAction.READ_ACTION)) {        
          outIsRead ="read";
        }else{
          outIsRead ="unread";
        }
        if (UpdateAlert.WORKFLOW_TYPE.equals((updateAlertSystemLog).getObjectType())){ 
          outStr += userName.equals(currentUserName)?userName: (userName+": "+currentUserName);
        }else { 
          outStr += userName; 
        } 
        outStr += " "+actionType;
        if (UpdateAlert.DOCUMENT_TYPE.equals((updateAlertSystemLog).getObjectType())){
          if ((updateAlertSystemLog).getRefObjectID()!=null){
            DmsDocument refDocument = docRetrievalManager.getDocument((updateAlertSystemLog).getRefObjectID());
            if(refDocument.getDocumentType().equals(DmsDocument.FOLDER_TYPE)){                        
               outStr += " "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectType_folder"); 
            }else{ 
               outStr += " "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectType_document"); 
            }
          }
        }else{
          outStr += " "+objectType; 
        }
        if (!Utility.isEmpty(status)){
          outStr += " "+status; 
        }
        if (UpdateAlert.DOCUMENT_TYPE.equals((updateAlertSystemLog).getObjectType())){ 
          //outStr += " "+"\"";
        }
/*        
        if (UpdateAlert.CALENDAR_TYPE.equals(((UpdateAlertSystemLog)updateAlertSystemLog).getObjectType())){ 
              outStr +=  " "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectName_calendar");
        }else if (UpdateAlert.WORKFLOW_TYPE.equals(((UpdateAlertSystemLog)updateAlertSystemLog).getObjectType())){ 
              outStr +=  " "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.log.objectName_workflow");
        }
*/        
        if (UpdateAlert.DOCUMENT_TYPE.equals((updateAlertSystemLog).getObjectType())||UpdateAlert.AUTOMATE_CHECKIN.equals((updateAlertSystemLog).getObjectType())){
          String sCurFunctionCode = docRetrievalManager.getCurFunctionCode(dmsDocument);
                    
          if ((updateAlertSystemLog).getRefObjectID()!=null){
            DmsDocument refDocument = docRetrievalManager.getDocument((updateAlertSystemLog).getRefObjectID());
            DmsDocument refRoot = docRetrievalManager.getRootFolderByRootID(refDocument.getRootID());
            String refPermission  = permissionManager.getPermission(dbConn,GlobalConstant.OBJECT_TYPE_DOCUMENT, refDocument.getID());
            String docItemStatus = (refDocument).getItemStatus();
            Integer checkPersonID = new Integer("0");
            if (DmsVersion.EXCLUSIVE_LOCK.equals(docItemStatus)) {
                DmsCheckoutHistory checkoutHistory = verControlManager.getCheckoutHistory((refDocument).getCheckoutID());
                checkPersonID = checkoutHistory.getCheckoutPersonID();
            }
            outStr += " "+(refDocument).getDocumentName();
//            outStr +=" \"";
            outStr +=  " "+underFolder;
//            outStr +=" \"";
          }
          outStr +=" "+docRetrievalManager.getLocationPath(dmsDocument.getID());
          
//          outStr +=" "+docRetrievalManager.getLocationPath(dmsDocument.getParentID())+"\\";
//          outStr += " "+((DmsDocument)dmsDocument).getDocumentName();
//          outStr +="\"";          
          if(forumManager.hasDiscussion(GlobalConstant.OBJECT_TYPE_DOCUMENT,((AbstractBaseObject)dmsDocument).getID()) || UpdateAlert.DISCUSS_ACTION.equals((updateAlertSystemLog).getActionType())){
              int totalTopic=forumManager.getTopicTotalByObject(GlobalConstant.OBJECT_TYPE_DOCUMENT,((AbstractBaseObject)dmsDocument).getID());
              int totalReply=forumManager.getReplyTotalByObject(GlobalConstant.OBJECT_TYPE_DOCUMENT,((AbstractBaseObject)dmsDocument).getID().toString());       
          }
        } else if (UpdateAlert.CALENDAR_TYPE.equals((updateAlertSystemLog).getObjectType())){ 
          if(!GlobalConstant.RECORD_STATUS_INACTIVE.equals(calendarRecord.getRecordStatus())){
            outURL += "/calendar/MaintCalendar.do?navMode=V&isHome=true&isHome=true&isHome=true&opReply=True&ID="+selectedID+"&systemLogID="+(updateAlertSystemLog).getID()+""+isReminded+"";
          }
          outStr += " "+objectName;
        } else if (UpdateAlert.WORKFLOW_TYPE.equals((updateAlertSystemLog).getObjectType())){ 
          outURL += "/workflow/MaintWorkflowTrack.do?showFullList=N&navMode=V&trackID="+trackID+"&ID="+recordID+"&from=home";
          outStr += " "+objectName;
        }
        if (UpdateAlert.DOCUMENT_TYPE.equals((updateAlertSystemLog).getObjectType())){ 
          //outStr +="\"";
        }   
         // For Delegation
        if (UpdateAlert.DELEGATION_TYPE.equals((updateAlertSystemLog).getObjectType())){
            UserDelegationDAObject delegationDAO = new UserDelegationDAObject(sessionContainer, dbConn);
            UserDelegation delegation = (UserDelegation) delegationDAO.getObjectByID((updateAlertSystemLog).getObjectID());    
            outStr += " [ "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "common.label.period_from") +TextUtility.formatTimestamp(calendarRecord.getDatetime())+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "common.label.period_to")
            +TextUtility.formatTimestamp(calendarRecord.getEndtime())+" ]";
        }
        if (UpdateAlert.CALENDAR_TYPE.equals((updateAlertSystemLog).getObjectType())){ 
          //if todo canlenar take out time part
          if (CalendarRecord.EVENT_TYPE_CALENDAR_TODO.equals(calendarRecord.getEventType())) { 
              outStr += " [ "+ TextUtility.formatTimestamp(calendarRecord.getDatetime()).substring(0,10) +" ]";
          }else{
              outStr += " [ "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "common.label.period_from") +TextUtility.formatTimestamp(calendarRecord.getDatetime())+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "common.label.period_to")
                        +TextUtility.formatTimestamp(calendarRecord.getEndtime())+" ]";
          }
        }
        if (UpdateAlert.REMIND_ACTION.equals((updateAlertSystemLog).getActionType())) {
          if(UpdateAlert.AUTOMATE_CHECKIN.equals((updateAlertSystemLog).getObjectType())){
            outStr += " "+checkIn;
          }else{
            outStr += " "+expired;
          }
        }
        outStr += " "+atOrBefore;
        outStr += " "+actionDate; 
        if (readDetails) {
           String message = TextUtility.escapeJSString((updateAlertSystemLog).getMessage());
           //if(!Utility.isEmpty(message)){
             outURL = "/ListUpdateAlertSummary.do?objectType=" + updateAlertSystemLog.getObjectType() + "&objectID=" + updateAlertSystemLog.getObjectID() + "&actionType=" + updateAlertSystemLog.getActionType() + "&updateAlertID=" + (updateAlertSystemLog).getUpdateAlertID() + "&updateAlertTypeID=" + (updateAlertSystemLog).getUpdateAlertTypeID() + "&updateAlertSystemLogID=" + (updateAlertSystemLog).getID() + "&message=&updateReadOperation=true";
           //}
        }
        //outDataTime = TextUtility.formatTimestamp(((UpdateAlertSystemLog)updateAlertSystemLog).getCreateDate());
        outDataTime = updateAlertSystemLog.getCreateDate().toString();
      }
        
        
      } catch(Exception e) {
        log.error(e, e);
      } finally {
          dbConn = null;
      } 
        
      outArrary[0] = outID;
      outArrary[1] = outIsRead;
      outArrary[2] = outStr;
      outArrary[3] = outURL;
      outArrary[4] = outDataTime;
      return outArrary;
  }
  
  public String[] getMessageLogNew (HttpServletRequest request ,UpdateAlertSystemLog updateAlertSystemLog){
     String[] outArrary = new String[5];
     String outID = updateAlertSystemLog.getID()+"";
     String outIsRead = "";
     String outStr = "";
     String outURL = "";
     String outDataTime = "";
     Connection dbConn = this.getConnection(request);
     SessionContainer  sessionContainer =this.getSessionContainer(request);
     MessageFormatterFactory formatter =  MessageFormatterFactory.getInstance();
     try{
    	 MessageFormatter messageFormatter = formatter.getMessageFormatter(updateAlertSystemLog,sessionContainer,dbConn);
    	 outIsRead = messageFormatter.isRead();
    	 if(outIsRead.equals("yes")){
    		 outIsRead = "isread";
    	 }else{
    		 outIsRead = "unread";
    	 }
    	 
    	 outStr =messageFormatter.getSubjectWithoutLink(); 
    	 outURL = "/"+messageFormatter.getUrlLink();
    	 outDataTime = updateAlertSystemLog.getCreateDate().toString();
     }catch(Exception e){
    	 
     }
      

    outArrary[0] = outID;
    outArrary[1] = outIsRead;
    outArrary[2] = outStr;
    outArrary[3] = outURL;
    outArrary[4] = outDataTime;
    return outArrary;
}
  
}
